import express from "express";
import _ from "lodash";

export default (db) => {
  const router = express.Router();

  // 通用CRUD生成器
  const createCRUDRoutes = (resource) => {
    // 获取所有
    router.get(`/${resource}`, async (req, res) => {
      try {
        await db.read(); // 确保读取最新数据
        res.json(db.data[resource] || []);
      } catch (error) {
        res.status(500).json({ error: "Database read failed" });
      }
    });

    // 获取单个
    router.get(`/${resource}/:id`, async (req, res) => {
      try {
        await db.read();
        const item = _.find(db.data[resource], { id: req.params.id });
        item ? res.json(item) : res.status(404).json({ error: "Not found" });
      } catch (error) {
        res.status(500).json({ error: "Database error" });
      }
    });

    // 创建
    router.post(`/${resource}`, async (req, res) => {
      try {
        await db.read();

        // 确保资源数组存在
        if (!db.data[resource]) {
          db.data[resource] = [];
        }

        const newItem = { ...req.body, id: Date.now().toString() };
        db.data[resource].push(newItem);
        await db.write();

        res.status(201).json(newItem);
      } catch (error) {
        res.status(500).json({ error: "Create failed" });
      }
    });

    // 更新
    router.put(`/${resource}/:id`, async (req, res) => {
      try {
        await db.read();
        const index = _.findIndex(db.data[resource], { id: req.params.id });

        if (index === -1) {
          return res.status(404).json({ error: "Not found" });
        }

        db.data[resource][index] = {
          ...db.data[resource][index],
          ...req.body,
        };

        await db.write();
        res.json(db.data[resource][index]);
      } catch (error) {
        res.status(500).json({ error: "Update failed" });
      }
    });

    // 删除
    router.delete(`/${resource}/:id`, async (req, res) => {
      try {
        await db.read();
        const initialLength = db.data[resource].length;

        db.data[resource] = db.data[resource].filter(
          (item) => item.id !== req.params.id
        );

        if (db.data[resource].length === initialLength) {
          return res.status(404).json({ error: "Not found" });
        }

        await db.write();
        res.status(204).end();
      } catch (error) {
        res.status(500).json({ error: "Delete failed" });
      }
    });
  };

  // 注册资源路由
  ["posts", "users", "comments"].forEach(createCRUDRoutes);

  return router;
};
